package com.orangelife.webservice.service.propFeeAccount.impl;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.activation.DataHandler;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.StreamingOutput;

import com.orangelife.service.propFeeAccount.impl.IImportExcel;
import jxl.CellView;
import jxl.Workbook;
import jxl.write.Label;
import jxl.write.NumberFormats;
import jxl.write.WritableCellFormat;
import jxl.write.WritableFont;

import org.apache.cxf.jaxrs.ext.multipart.Attachment;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Service;

import com.github.pagehelper.Page;
import com.orangelife.exception.AppBizException;
import com.orangelife.redis.core.redis.session.redisSession.RedisSessionFactory;
import com.orangelife.redis.core.redis.session.redisSession.WebServiceSession;
import com.orangelife.service.cerHouseholder.ICerHouseholderService;
import com.orangelife.service.propFeeAccount.IPropFeeAccountService;
import com.orangelife.service.propFeeAccount.impl.IImportAccount;
import com.orangelife.service.propFeeAccount.model.PropFeeAccountDto;
import com.orangelife.service.propFeeAccountImportLog.IPropFeeAccountImportLogService;
import com.orangelife.service.propFeeAmountLog.IPropFeeAmountLogService;
import com.orangelife.service.propFeeComm.IPropFeeCommService;
import com.orangelife.service.propFeeComm.model.PropFeeCommDto;
import com.orangelife.service.propFeeDic.IPropFeeDicService;
import com.orangelife.service.propFeeDic.model.PropFeeDicDto;
import com.orangelife.setting.constant.CodeConst;
import com.orangelife.setting.constant.InfoConst;
import com.orangelife.utils.JSONHelper;
import com.orangelife.utils.PropertyUtils;
import com.orangelife.utils.StringUtils;
import com.orangelife.webservice.base.BaseService;
import com.orangelife.webservice.base.PageUtils;
import com.orangelife.webservice.service.propFeeAccount.IPropFeeAccountWebService;

@Service("propFeeAccountWebService")
public class PropFeeAccountWebServiceImpl extends BaseService implements
		IPropFeeAccountWebService {

	@Resource(name = "propFeeAccountService")
	private IPropFeeAccountService propFeeAccountService;
	@Resource(name = "importAccount")
	private IImportAccount importAccount;
	@Resource(name="importExcel")
	private IImportExcel importExcel;
	@Resource(name = "propFeeCommService")
	private IPropFeeCommService propFeeCommService;
	@Resource(name = "propFeeAmountLogService")
	private IPropFeeAmountLogService propFeeAmountLogService;
	@Resource(name = "propFeeAccountImportLogService")
	private IPropFeeAccountImportLogService propFeeAccountImportLogService;

	@Resource(name = "cerHouseholderService")
	private ICerHouseholderService cerHouseholderService;
	@Resource(name = "propFeeDicService")
	private IPropFeeDicService propFeeDicService;

	@Override
	public Response getAmonutByApartmentID(HttpServletRequest request,
			String commID, String apartmentID) throws Exception,
			AppBizException {

		PropFeeAccountDto pfa = propFeeAccountService
				.findAccountByApartID(apartmentID);

		Map<String, Object> res = new HashMap<String, Object>();

		if (pfa != null) {
			if ("1".equals(pfa.getStatus())) {
				res.put("amount", pfa.getMoney());
				res.put("apartmentID", apartmentID);
			}

		}

		// TODO Auto-generated method stub
		return this.normalResp(res);

	}

	@Override
	public Response addPropFeeAccount(HttpServletRequest servletRequest,
			PropFeeAccountDto propFeeAccount) throws Exception {

		/************************************************
		 * 检查session
		 ************************************************/
		PageUtils pageUtils = this.validateLogin(servletRequest);

		if (pageUtils.getResponse() != null) {
			return pageUtils.getResponse();
		}

		int result = propFeeAccountService.addPropFeeAccount(propFeeAccount);
		if (!(result > 0)) {
			return this.abnormalResp(CodeConst.BIS_CODE_13006,
					InfoConst.BIS_INFO_13006);
		}
		logger.info(pageUtils.getBaseSession().getLoginName() + "在"
				+ pageUtils.getBaseSession().getLoginType() + "端" + new Date()
				+ "时" + "添加实体成功");

		return this.normalResp();
	}

	@Override
	public Response editPropFeeAccount(HttpServletRequest servletRequest,
			PropFeeAccountDto propFeeAccount) throws Exception {
		/************************************************
		 * 检查session
		 ************************************************/
		PageUtils pageUtils = this.validateLogin(servletRequest);

		if (pageUtils.getResponse() != null) {
			return pageUtils.getResponse();
		}
		/************************************************
		 * 输入参数ID检查
		 ************************************************/
		Response error = this.validateUUId(propFeeAccount.getAccountID(),
				"accountID");
		if (error != null) {
			return error;
		}

		/************************************************
		 * 输入参数检查
		 ************************************************/
		// TODO;
		propFeeAccount.setCreateuserUser(StringUtils.isBlank(pageUtils
				.getBaseSession().getRealname()) ? pageUtils.getBaseSession()
				.getTrueName() : pageUtils.getBaseSession().getRealname());
		propFeeAccount.setCreateuserID(pageUtils.getBaseSession().getUserID());
		int result = propFeeAccountService.editPropFeeAccount(propFeeAccount);
		if (!(result > 0)) {
			return this.abnormalResp(CodeConst.BIS_CODE_13006,
					InfoConst.BIS_INFO_13006);
		}
		logger.info(pageUtils.getBaseSession().getLoginName() + "在"
				+ pageUtils.getBaseSession().getLoginType() + "端" + new Date()
				+ "时" + "修改实体成功");

		return this.normalResp();
	}

	@Override
	public Response deletePropFeeAccount(HttpServletRequest servletRequest,
			String accountID) throws Exception {
		/************************************************
		 * 检查session
		 ************************************************/
		PageUtils pageUtils = this.validateLogin(servletRequest);

		if (pageUtils.getResponse() != null) {
			return pageUtils.getResponse();
		}
		/************************************************
		 * 输入参数ID检查
		 ************************************************/
		Response error = this.validateUUId(accountID, "accountID");
		if (error != null) {
			return error;
		}
		int result = propFeeAccountService
				.deletePropFeeAccountByLogic(accountID);
		if (!(result > 0)) {
			return this.abnormalResp(CodeConst.BIS_CODE_13006,
					InfoConst.BIS_INFO_13006);
		}
		logger.info(pageUtils.getBaseSession().getLoginName() + "在"
				+ pageUtils.getBaseSession().getLoginType() + "端" + new Date()
				+ "时" + "删除实体成功");

		return this.normalResp();
	}

	@Override
	public Response findPropFeeAccountByID(HttpServletRequest servletRequest,
			String accountID) throws Exception {

		/************************************************
		 * 检查session
		 ************************************************/
		PageUtils pageUtils = this.validateLogin(servletRequest);

		if (pageUtils.getResponse() != null) {
			return pageUtils.getResponse();
		}
		/************************************************
		 * 输入参数ID检查
		 ************************************************/
		Response error = this.validateUUId(accountID, "accountID");
		if (error != null) {
			return error;
		}
		PropFeeAccountDto propFeeAccount = propFeeAccountService
				.findPropFeeAccountByID(accountID);

		logger.info(pageUtils.getBaseSession().getLoginName() + "在"
				+ pageUtils.getBaseSession().getLoginType() + "端" + new Date()
				+ "时" + "查询实体成功");
		return this.normalResp(propFeeAccount);
	}

	@Override
	public Response getAllPropFeeAccount(HttpServletRequest servletRequest,
			String commID, String search, String tsCreate, String pageIndex,
			String pageSize) throws Exception {

		PageUtils pageUtils = this.validatePageAndSetPage(servletRequest,
				pageIndex, pageSize);
		if (pageUtils.getResponse() != null) {
			return pageUtils.getResponse();
		}

		if (!StringUtils.isBlank(tsCreate)) {
			StringUtils.isTime(tsCreate);
			tsCreate = String.valueOf(Long.parseLong(tsCreate) / 1000);
		}
		/************************************************
		 * 查询列表
		 ************************************************/
		List<Map<String, Object>> list = propFeeAccountService
				.findPropFeeAccountByPage(commID, tsCreate == null ? null
						: tsCreate, search == null ? null : search, pageUtils
						.getiPageIndex(), pageUtils.getiPageSize());

		/************************************************
		 * 返回结果设定
		 ************************************************/
		Long total = ((Page<Map<String, Object>>) list).getTotal();

		logger.info(pageUtils.getBaseSession().getLoginName() + "在"
				+ pageUtils.getBaseSession().getLoginName() + new Date()
				+ "查询实体成功");

		return this.normalResp(pageUtils.getiPageIndex(),
				pageUtils.getiPageSize(), total,
				PropertyUtils.turnToEntity(list));
	}

	@Override
	public Response bauthFindPropFeeAccount(HttpServletRequest servletRequest,
			List<String> propFeeAccount) throws Exception {

		Map<String, Object> map = new HashMap<String, Object>();
		/************************************************
		 * 根据批量查询
		 ************************************************/
		try {

			/************************************************
			 * 输入参数ID检查
			 ************************************************/
			if (propFeeAccount == null || propFeeAccount.size() <= 0) {
				logger.error(InfoConst.SYS_INFO_1001, "亲，请输入相关的参数");
				return this.abnormalResp(CodeConst.SYS_CODE_1001,
						InfoConst.SYS_INFO_1001, "亲，请输入相关的参数");
			}

			map.put("pageEntity", propFeeAccountService
					.bauthfindPropFeeAccount(propFeeAccount));
			map.put("errInfo", "ok");
			map.put("errCode", "0");
		} catch (AppBizException e) {
			map.put("errInfo", e.getMessage());
			map.put("errCode", e.getCode());
		}

		return Response.ok(map).build();

	}

	@Override
	public Response bauthFindPropFeeAccounts(HttpServletRequest servletRequest,
			Map<String, Object> propFeeAccount) throws Exception {

		Map<String, Object> map = new HashMap<String, Object>();
		/************************************************
		 * 根据批量查询
		 ************************************************/
		try {

			/************************************************
			 * 输入参数ID检查
			 ************************************************/
			if (propFeeAccount == null || propFeeAccount.size() <= 0) {
				logger.error(InfoConst.SYS_INFO_1001, "亲，请输入相关的参数");
				return this.abnormalResp(CodeConst.SYS_CODE_1001,
						InfoConst.SYS_INFO_1001, "亲，请输入相关的参数");
			}

			map.put("pageEntity", PropertyUtils
					.turnToEntity(propFeeAccountService
							.bauthfindPropFeeAccountByMap(propFeeAccount)));
			map.put("errInfo", "ok");
			map.put("errCode", "0");
		} catch (AppBizException e) {
			map.put("errInfo", e.getMessage());
			map.put("errCode", e.getCode());
		}

		return Response.ok(map).build();

	}

	@Override
	public Response clearCache(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		propFeeAccountService.clearCache();
		return this.normalResp();
	}

	@Override
	public Response downRecord(HttpServletRequest servletRequest,
			final HttpServletResponse servletResponse, String search,
			String commID, final String comm) throws Exception {

		if (StringUtils.isBlank(commID)) {
			throw new AppBizException(2, "亲小区信息");
		}
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("commID", commID);

		/************************************************
		 * 返回结果设定
		 ************************************************/

		final PropFeeCommDto propFeeComm = propFeeCommService
				.findPropFeeCommByID(commID);
		String info = "楼栋,单元,房号,金额";

		SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
		final String filename = df.format(new Date());
		StreamingOutput stream = null;

		final String infos[] = info.split(",");
		stream = new StreamingOutput() {
			public void write(OutputStream output) throws IOException,
					WebApplicationException {
				try {
					servletResponse.setContentType("application/vnd.ms-excel");
					servletResponse.setHeader(
							"Content-Disposition",
							"attachment; filename="
									+ new String((propFeeComm.getComm()
											+ "缴费账户余额表" + filename + ".xls")
											.getBytes("UTF-8"), "iso8859-1"));
					servletResponse.setHeader("Pragma", "No-cache");
					servletResponse.setHeader("Cache-Control", "No-cache");
					servletResponse.setDateHeader("Expires", 0); // 这个地方一定要进行编码的转换要不然中文字符会出现乱码.
					// 设置下载头信息.end,
					// SimpleDateFormat df = new
					// SimpleDateFormat("yyyy-MM-dd");

					InputStream fis = null;
					// PrintWriter out = response.getWriter();
					try {
						output = servletResponse.getOutputStream();
						jxl.write.WritableWorkbook wwb = Workbook
								.createWorkbook(output);

						jxl.write.WritableFont wfont = new jxl.write.WritableFont(
								WritableFont.createFont("宋体"), 12);
						WritableCellFormat font = new WritableCellFormat(wfont);
						font.setAlignment(jxl.format.Alignment.CENTRE);
						font.setVerticalAlignment(jxl.format.VerticalAlignment.CENTRE);
						// 水平居中对齐

						// 竖直方向居中对齐
						jxl.write.WritableSheet ws = wwb.createSheet("Sheet1",
								1); // 设置标题.ws.addCell(new
						for (int l = 0; l < infos.length; l++) {
							ws.addCell(new Label(l, 0, infos[l], font));
							if (l == 0) {

								CellView cv = new CellView(); // 定义一个列显示样式
								cv.setFormat(font);// 把定义的单元格格式初始化进去
								cv.setSize(10 * 265);// 设置列宽度（不设置的话是0，不会显示）

								ws.setColumnView(l, cv);
							} else {
								CellView cv = new CellView(); // 定义一个列显示样式
								cv.setFormat(font);// 把定义的单元格格式初始化进去
								cv.setSize(50 * 265);// 设置列宽度（不设置的话是0，不会显示）
								ws.setColumnView(l, cv);
							}
						}

						wwb.write();
						if (wwb != null) {
							wwb.close();
						}
					} catch (Exception e) {
						e.printStackTrace();
					} finally {// 正常关闭输入输出流.
						if (fis != null) {
							fis.close();
						}
						if (output != null) {
							output.flush();
							output.close();
						}

					}

				} catch (Exception e) {
					e.printStackTrace();
					throw new WebApplicationException(e);

				}
			}
		};

		return Response.ok(stream, MediaType.APPLICATION_OCTET_STREAM).build();
	}

	@Override
	public Response ImportAccount(HttpServletRequest servletRequest,
			HttpServletResponse servletResponse, String commID,
			String accessToken, List<Attachment> attachments) throws Exception {

		WebServiceSession webServiceSession = RedisSessionFactory.getRedisSession(accessToken);

		if (webServiceSession == null) {
			return this.abnormalResp(CodeConst.SYS_CODE_2001,
					InfoConst.SYS_INFO_2001);
		}
		String fileName = "";
		if (attachments == null || attachments.size() == 0) {
			throw new AppBizException(100002, "请选择要上传的文件");
		}
		if (StringUtils.isBlank(commID)) {
			throw new AppBizException(2, "亲，小区信息");
		}
		Sheet sheet = null;
		for (Attachment attachment : attachments) {

			DataHandler item = attachment.getDataHandler();
			fileName = item.getName();
			InputStream inputStream = item.getInputStream();
			fileName = new String(fileName.getBytes("iso-8859-1"), "utf-8");

			org.apache.poi.ss.usermodel.Workbook book = null;

			if (fileName.endsWith(".xls")) {
				book = new HSSFWorkbook(inputStream);
			} else if (fileName.endsWith(".xlsx")) {
				book = new XSSFWorkbook(inputStream);
			} else {
				throw new AppBizException(100002, "文件格式错误");
			}
			sheet = book.getSheetAt(0);// 第一个工作表
			//importAccount.importAccount(commID, sheet, webServiceSession, fileName);
			importExcel.importExcel(commID, sheet, webServiceSession, fileName,"account");
		}

		return this.normalResp();

	}

	@Override
	public Response getAccountlogs(HttpServletRequest servletRequest,
			String accountID, String operation, String logType, String search,
			String tsCreate, String pageIndex, String pageSize)
			throws Exception {

		PageUtils pageUtils = this.validatePageAndSetPage(servletRequest,
				pageIndex, pageSize);
		if (pageUtils.getResponse() != null) {
			return pageUtils.getResponse();
		}

		if (!StringUtils.isBlank(tsCreate)) {
			StringUtils.isTime(tsCreate);
			tsCreate = String.valueOf(Long.parseLong(tsCreate) / 1000);
		}
		/************************************************
		 * 查询列表
		 ************************************************/
		List<Map<String, Object>> list = propFeeAmountLogService
				.findPropFeeAmountLogByPage(accountID, operation, logType,
						tsCreate == null ? null : tsCreate,
						search == null ? null : search, pageUtils
								.getiPageIndex(), pageUtils.getiPageSize());

		/************************************************
		 * 返回结果设定
		 ************************************************/
		Long total = ((Page<Map<String, Object>>) list).getTotal();
		list = PropertyUtils.turnToEntity(list);

		if (list != null && list.size() > 0) {
			for (Map<String, Object> map : list) {

				if (map.get("operation") != null && map.get("money") != null
						&& map.get("totalMoney") != null) {

					if (map.get("operation").toString().equals("1")) {
						map.put("subMoney",
								new BigDecimal(map.get("money").toString())
										.add(new BigDecimal(map.get(
												"totalMoney").toString()))
										.setScale(2, BigDecimal.ROUND_HALF_UP));
					}
					if (map.get("operation").toString().equals("2")) {
						map.put("subMoney",
								new BigDecimal(map.get("totalMoney").toString())
										.subtract(
												new BigDecimal(map.get("money")
														.toString())).setScale(
												2, BigDecimal.ROUND_HALF_UP));
					}
				}

			}
		}

		logger.info(pageUtils.getBaseSession().getLoginName() + "在"
				+ pageUtils.getBaseSession().getLoginName() + new Date()
				+ "查询实体成功");

		return this.normalResp(pageUtils.getiPageIndex(),
				pageUtils.getiPageSize(), total, list);
	}

	@Override
	public Response getAccountImportlogs(HttpServletRequest servletRequest,
			String commID, String search, String tsCreate, String pageIndex,
			String pageSize) throws Exception {

		PageUtils pageUtils = this.validatePageAndSetPage(servletRequest,
				pageIndex, pageSize);
		if (pageUtils.getResponse() != null) {
			return pageUtils.getResponse();
		}

		if (!StringUtils.isBlank(tsCreate)) {
			StringUtils.isTime(tsCreate);
			tsCreate = String.valueOf(Long.parseLong(tsCreate) / 1000);
		}
		/************************************************
		 * 查询列表
		 ************************************************/
		List<Map<String, Object>> list = propFeeAccountImportLogService
				.findPropFeeAccountImportLogByPage(commID, tsCreate, search,
						pageUtils.getiPageIndex(), pageUtils.getiPageSize());

		/************************************************
		 * 返回结果设定
		 ************************************************/
		Long total = ((Page<Map<String, Object>>) list).getTotal();

		logger.info(pageUtils.getBaseSession().getLoginName() + "在"
				+ pageUtils.getBaseSession().getLoginName() + new Date()
				+ "查询实体成功");

		return this.normalResp(pageUtils.getiPageIndex(),
				pageUtils.getiPageSize(), total,
				PropertyUtils.turnToEntity(list));
	}

	@Override
	public Response getAllPropFeeAccountInfo(HttpServletRequest servletRequest,
			String commID, String apartmentType, String searchType,
			String search, String startTime, String pageIndex, String pageSize)
			throws Exception {

		PageUtils pageUtils = this.validatePageAndSetPage(servletRequest,
				pageIndex, pageSize);
		if (pageUtils.getResponse() != null) {
			return pageUtils.getResponse();
		}

		/************************************************
		 * 查询列表
		 ************************************************/
		List<Map<String, Object>> list = propFeeAccountService
				.getAllPropFeeAccountInfo(commID, apartmentType, searchType,
						search, startTime, pageUtils.getiPageIndex(),
						pageUtils.getiPageSize());

		/************************************************
		 * 返回结果设定
		 ************************************************/
		Long total = ((Page<Map<String, Object>>) list).getTotal();

		logger.info(pageUtils.getBaseSession().getLoginName() + "在"
				+ pageUtils.getBaseSession().getLoginName() + new Date()
				+ "查询实体成功");

		return this.normalResp(pageUtils.getiPageIndex(),
				pageUtils.getiPageSize(), total,
				PropertyUtils.turnToEntity(list));
	}

	@Override
	public Response getAccountInfologs(HttpServletRequest servletRequest,
			String accountID, String operation, String logType, String search,
			String tsCreate, String pageIndex, String pageSize)
			throws Exception {

		PageUtils pageUtils = this.validatePageAndSetPage(servletRequest,
				pageIndex, pageSize);
		if (pageUtils.getResponse() != null) {
			return pageUtils.getResponse();
		}

		if (!StringUtils.isBlank(tsCreate)) {
			StringUtils.isTime(tsCreate);
			tsCreate = String.valueOf(Long.parseLong(tsCreate) / 1000);
		}
		/************************************************
		 * 查询列表
		 ************************************************/
		List<Map<String, Object>> list = propFeeAmountLogService
				.findPropFeeAmountLogs(accountID, operation, logType,
						tsCreate == null ? null : tsCreate,
						search == null ? null : search, pageUtils
								.getiPageIndex(), pageUtils.getiPageSize());

		/************************************************
		 * 返回结果设定
		 ************************************************/
		Long total = ((Page<Map<String, Object>>) list).getTotal();
		list = PropertyUtils.turnToEntity(list);

		if (list != null && list.size() > 0) {
 			for (Map<String, Object> map : list) {

				if (map.get("operation") != null && map.get("money") != null
						&& map.get("totalMoney") != null) {

					if (map.get("operation").toString().equals("1")) {
						map.put("subMoney",
								new BigDecimal(map.get("money").toString())
										.add(new BigDecimal(map.get(
												"totalMoney").toString()))
										.setScale(2, BigDecimal.ROUND_HALF_UP));
					}
					if (map.get("operation").toString().equals("2")) {
						map.put("subMoney",
								new BigDecimal(map.get("totalMoney").toString())
										.subtract(
												new BigDecimal(map.get("money")
														.toString())).setScale(
												2, BigDecimal.ROUND_HALF_UP));
					}
				}

			}
		}

		logger.info(pageUtils.getBaseSession().getLoginName() + "在"
				+ pageUtils.getBaseSession().getLoginName() + new Date()
				+ "查询实体成功");

		return this.normalResp(pageUtils.getiPageIndex(),
				pageUtils.getiPageSize(), total, list);
	}

	@Override
	public Response exportAccount(HttpServletRequest servletRequest,
			final HttpServletResponse servletResponse, String commID,
			String comm, String apartmentType, String searchType,
			String search, String startTime) throws Exception {

		if (StringUtils.isBlank(commID)) {
			throw new AppBizException(2, "亲小区信息");
		}
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("commID", commID);

		/************************************************
		 * 返回结果设定
		 ************************************************/

		final PropFeeCommDto propFeeComm = propFeeCommService
				.findPropFeeCommByID(commID);

		final List<Map<String, Object>> list = PropertyUtils
				.turnToEntity(propFeeAccountService.getAllPropFeeAccountInfo(
						commID, apartmentType, searchType, search, startTime));

		String info = "小区名称,产权类型,户号,业主姓名,月初余额(元),本月预存额(元),本月冲抵额(元),月末余额(元)";
		final String apartmentTypes[] = { "", "车位", "住宅", "商铺", "商场", "写字楼" };
		SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
		final String filename = df.format(new Date());
		StreamingOutput stream = null;

		final String infos[] = info.split(",");
		stream = new StreamingOutput() {
			public void write(OutputStream output) throws IOException,
					WebApplicationException {
				try {
					servletResponse.setContentType("application/vnd.ms-excel");
					servletResponse.setHeader(
							"Content-Disposition",
							"attachment; filename="
									+ new String((propFeeComm.getComm()
											+ "房屋账户余额" + filename + ".xls")
											.getBytes("UTF-8"), "iso8859-1"));
					servletResponse.setHeader("Pragma", "No-cache");
					servletResponse.setHeader("Cache-Control", "No-cache");
					servletResponse.setDateHeader("Expires", 0);
					InputStream fis = null;
					try {
						output = servletResponse.getOutputStream();
						jxl.write.WritableWorkbook wwb = Workbook
								.createWorkbook(output);

						jxl.write.WritableFont wfont = new jxl.write.WritableFont(
								WritableFont.createFont("宋体"), 12);

						WritableCellFormat font = new WritableCellFormat(
								NumberFormats.TEXT);
						font.setFont(wfont);
						font.setAlignment(jxl.format.Alignment.CENTRE);
						font.setVerticalAlignment(jxl.format.VerticalAlignment.CENTRE);
						// 水平居中对齐

						// 竖直方向居中对齐

						jxl.write.WritableSheet ws = wwb.createSheet("Sheet1",
								1); // 设置标题.ws.addCell(new
						for (int l = 0; l < infos.length; l++) {
							ws.addCell(new Label(l, 0, infos[l], font));
							if (l == 0 || l == 1) {

								CellView cv = new CellView(); // 定义一个列显示样式
								cv.setFormat(font);// 把定义的单元格格式初始化进去
								cv.setSize(50 * 265);// 设置列宽度（不设置的话是0，不会显示）

								ws.setColumnView(l, cv);
							} else {
								CellView cv = new CellView(); // 定义一个列显示样式
								cv.setFormat(font);// 把定义的单元格格式初始化进去
								cv.setSize(50 * 265);// 设置列宽度（不设置的话是0，不会显示）
								ws.setColumnView(l, cv);
							}
						}
						for (int j = 0; j < list.size(); j++) {
							Map<String, Object> map = PropertyUtils
									.turnToEntity1(list.get(j));
							int i = 0;

							ws.addCell(new Label(i, j + 1,
									map.get("comm") != null ? map.get("comm")
											.toString() : null, font));

							ws.addCell(new Label(
									i + 1,
									j + 1,
									map.get("apartmentType") != null ? apartmentTypes[Integer
											.parseInt(map.get("apartmentType")
													.toString())] : null, font));

							StringBuffer houseInfo = new StringBuffer();
							houseInfo.append(map.get("buildingName") + "-");
							if (map.get("unitName") != null) {
								houseInfo.append(map.get("unitName")).append(
										"-");
							}
							houseInfo.append(map.get("apartmentNum"));
							ws.addCell(new Label(i + 2, j + 1, houseInfo
									.toString(), font));
							ws.addCell(new Label(i + 3, j + 1,
									map.get("name") != null ? map.get("name")
											.toString() : null, font));
							ws.addCell(new Label(i + 4, j + 1, map
									.get("startMoonMoney") != null ? map.get(
									"startMoonMoney").toString() : null, font));
							ws.addCell(new Label(i + 5, j + 1, map
									.get("preMoonMoney") != null ? map.get(
									"preMoonMoney").toString() : null, font));
							ws.addCell(new Label(i + 6, j + 1, map
									.get("offMoonMoney") != null ? map.get(
									"offMoonMoney").toString() : null, font));
							ws.addCell(new Label(i + 7, j + 1, map
									.get("endMoonMoney") != null ? map.get(
									"endMoonMoney").toString() : null, font));

						}
						wwb.write();
						if (wwb != null) {
							wwb.close();
						}
					} catch (Exception e) {
						e.printStackTrace();
					} finally {// 正常关闭输入输出流.
						if (fis != null) {
							fis.close();
						}
						if (output != null) {
							output.flush();
							output.close();
						}

					}

				} catch (Exception e) {
					e.printStackTrace();
					throw new WebApplicationException(e);

				}
			}
		};

		return Response.ok(stream, MediaType.APPLICATION_OCTET_STREAM).build();
	}

	@Override
	public Response exportAccountLogs(HttpServletRequest servletRequest,
			final HttpServletResponse servletResponse, String accountID,
			String commID, String apartmentID, String operation,
			String logType, String search) throws Exception {

		if (StringUtils.isBlank(commID)) {
			throw new AppBizException(2, "亲小区信息");
		}
		Map<String, Object> propFeeComm = cerHouseholderService
				.getHouseInfo(apartmentID);

		final StringBuffer houseInfo = new StringBuffer();
		houseInfo.append(propFeeComm.get("buildingName") + "-");
		if (propFeeComm.get("unitName") != null) {
			houseInfo.append(propFeeComm.get("unitName")).append("-");
		}
		houseInfo.append(propFeeComm.get("apartmentNum")).append("-");

		/************************************************
		 * 返回结果设定
		 ************************************************/

		List<PropFeeDicDto> propFeeDics = propFeeDicService
				.findPropFeeDicByRelevantID(null, null, "PAYTYPE");
		if (propFeeDics == null || propFeeDics.size() <= 0) {
			throw new AppBizException(2, "缴费支付方式");
		}

		/**
		 * 
		 * 结算方式（'0现金',1 '刷卡',2 '银行转账', 3"橙子生活代缴",4 "支付宝缴费",5,折减优惠,6押金转存，7预存冲抵）*
		 **/

		final List<Map<String, Object>> list = PropertyUtils
				.turnToEntity(propFeeAmountLogService.findPropFeeAmountLogs(
						accountID, operation, logType, search));

		final String payWays[] = getPayName();// { "现金", "刷卡", "银行转账", "橙子生活",
												// "支付宝缴费",
		// "折减优惠",
		// "押金转存", "预存冲抵" };
		String info = "收费项目,费用归属月份,支付方式,操作前金额（元）,预存/抵扣金额（元）,账户余额（元）,时间";
		final String apartmentTypes[] = { "", "车位", "住宅", "商铺", "商场", "写字楼" };
		SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
		final String filename = df.format(new Date());
		StreamingOutput stream = null;

		final String infos[] = info.split(",");
		stream = new StreamingOutput() {
			public void write(OutputStream output) throws IOException,
					WebApplicationException {
				try {
					servletResponse.setContentType("application/vnd.ms-excel");
					servletResponse.setHeader(
							"Content-Disposition",
							"attachment; filename="
									+ new String((houseInfo + "账户流水明细"
											+ filename + ".xls")
											.getBytes("UTF-8"), "iso8859-1"));
					servletResponse.setHeader("Pragma", "No-cache");
					servletResponse.setHeader("Cache-Control", "No-cache");
					servletResponse.setDateHeader("Expires", 0);
					InputStream fis = null;
					try {
						output = servletResponse.getOutputStream();
						jxl.write.WritableWorkbook wwb = Workbook
								.createWorkbook(output);

						jxl.write.WritableFont wfont = new jxl.write.WritableFont(
								WritableFont.createFont("宋体"), 12);

						WritableCellFormat font = new WritableCellFormat(
								NumberFormats.TEXT);
						font.setFont(wfont);
						font.setAlignment(jxl.format.Alignment.CENTRE);
						font.setVerticalAlignment(jxl.format.VerticalAlignment.CENTRE);
						// 水平居中对齐

						// 竖直方向居中对齐

						jxl.write.WritableSheet ws = wwb.createSheet("Sheet1",
								1); // 设置标题.ws.addCell(new
						for (int l = 0; l < infos.length; l++) {
							ws.addCell(new Label(l, 0, infos[l], font));
							if (l == 0 || l == 1) {

								CellView cv = new CellView(); // 定义一个列显示样式
								cv.setFormat(font);// 把定义的单元格格式初始化进去
								cv.setSize(50 * 265);// 设置列宽度（不设置的话是0，不会显示）

								ws.setColumnView(l, cv);
							} else {
								CellView cv = new CellView(); // 定义一个列显示样式
								cv.setFormat(font);// 把定义的单元格格式初始化进去
								cv.setSize(50 * 265);// 设置列宽度（不设置的话是0，不会显示）
								ws.setColumnView(l, cv);
							}
						}
						for (int j = 0; j < list.size(); j++) {
							Map<String, Object> map = PropertyUtils
									.turnToEntity1(list.get(j));
							int i = 0;
							ws.addCell(new Label(i, j + 1,
									map.get("item") != null ? map.get("item")
											.toString() : null, font));

							if (map.get("logContent") != null) {

								if (!StringUtils.isBlank(map.get("logContent")
										.toString())) {
									Map<String, Object> orderInfo = JSONHelper
											.jsonToMap(map.get("logContent")
													.toString());
									ws.addCell(new Label(
											i + 1,
											j + 1,
											orderInfo.get("feeDate").toString(),
											font));
								} else {
									ws.addCell(new Label(i + 1, j + 1, null,
											font));
								}
							} else {
								ws.addCell(new Label(i + 1, j + 1, null, font));
							}
							ws.addCell(new Label(
									i + 2,
									j + 1,
									map.get("statementType") != null ? payWays[Integer
											.parseInt(map.get("statementType")
													.toString())] : null, font));
							ws.addCell(new Label(i + 3, j + 1, map
									.get("totalMoney") != null ? map.get(
									"totalMoney").toString() : null, font));

							if (map.get("operation").toString().equals("1")) {
								ws.addCell(new Label(i + 4, j + 1, map
										.get("money") != null ? "+"
										+ map.get("money").toString() : null,
										font));
							}
							if (map.get("operation").toString().equals("2")) {
								ws.addCell(new Label(i + 4, j + 1, map
										.get("money") != null ? "-"
										+ map.get("money").toString() : null,
										font));
							}
							ws.addCell(new Label(i + 5, j + 1, map
									.get("subMoney") != null ? map.get(
									"subMoney").toString() : null, font));

							ws.addCell(new Label(i + 6, j + 1, map
									.get("tscreate") != null ? map
									.get("tscreate")
									.toString()
									.substring(
											0,
											map.get("tscreate").toString()
													.indexOf("."))

							: null, font));

						}
						wwb.write();
						if (wwb != null) {
							wwb.close();
						}
					} catch (Exception e) {
						e.printStackTrace();
					} finally {// 正常关闭输入输出流.
						if (fis != null) {
							fis.close();
						}
						if (output != null) {
							output.flush();
							output.close();
						}

					}

				} catch (Exception e) {
					e.printStackTrace();
					throw new WebApplicationException(e);

				}
			}
		};

		return Response.ok(stream, MediaType.APPLICATION_OCTET_STREAM).build();
	}

	@Override
	public Response getSumAccountInfo(HttpServletRequest servletRequest,
			String commID, String apartmentType, String searchType,
			String search, String startTime) throws Exception {
		/************************************************
		 * 检查session
		 ************************************************/
		PageUtils pageUtils = this.validateLogin(servletRequest);

		if (pageUtils.getResponse() != null) {
			return pageUtils.getResponse();
		}
		/************************************************
		 * 输入参数ID检查
		 ************************************************/

		Map<String, Object> reMap = propFeeAccountService.getSumAccountInfo(
				commID, apartmentType, searchType, search, startTime);
		return this.normalResp(reMap);
	}

	@Override
	public Response accountlogs(HttpServletRequest servletRequest,
			String accountID, String operation, String logType, String search,
			String tsCreate, String pageIndex, String pageSize)
			throws Exception {
		PageUtils pageUtils = this.validatePageAndSetPage(servletRequest,
				pageIndex, pageSize);
		if (pageUtils.getResponse() != null) {
			return pageUtils.getResponse();
		}

		if (!StringUtils.isBlank(tsCreate)) {
			StringUtils.isTime(tsCreate);
			tsCreate = String.valueOf(Long.parseLong(tsCreate) / 1000);
		}
		/************************************************
		 * 查询列表
		 ************************************************/
		List<Map<String, Object>> list = propFeeAmountLogService
				.findPropFeeAmountLogsForExport(accountID, operation, logType,
						tsCreate == null ? null : tsCreate,
						search == null ? null : search, pageUtils
								.getiPageIndex(), pageUtils.getiPageSize());

		/************************************************
		 * 返回结果设定
		 ************************************************/
		Long total = ((Page<Map<String, Object>>) list).getTotal();
		list = PropertyUtils.turnToEntity(list);

		if (list != null && list.size() > 0) {
			for (Map<String, Object> map : list) {

				if (map.get("operation") != null && map.get("money") != null
						&& map.get("totalMoney") != null) {

					if (map.get("operation").toString().equals("1")) {
						map.put("subMoney",
								new BigDecimal(map.get("money").toString())
										.add(new BigDecimal(map.get(
												"totalMoney").toString()))
										.setScale(2, BigDecimal.ROUND_HALF_UP));
					}
					if (map.get("operation").toString().equals("2")) {
						map.put("subMoney",
								new BigDecimal(map.get("totalMoney").toString())
										.subtract(
												new BigDecimal(map.get("money")
														.toString())).setScale(
												2, BigDecimal.ROUND_HALF_UP));
					}
				}

			}
		}

		logger.info(pageUtils.getBaseSession().getLoginName() + "在"
				+ pageUtils.getBaseSession().getLoginName() + new Date()
				+ "查询实体成功");

		return this.normalResp(pageUtils.getiPageIndex(),
				pageUtils.getiPageSize(), total, list);
	}

	public String[] getPayName() throws AppBizException {

		List<PropFeeDicDto> propFeeDics = propFeeDicService
				.findPropFeeDicByRelevantID(null, null, "payWay");
		if (propFeeDics == null || propFeeDics.size() <= 0) {
			throw new AppBizException(2, "缴费支付方式");
		}
		List<String> payNames = new ArrayList<String>();
		/**
		 * 
		 * 结算方式（'0现金',1 '刷卡',2 '银行转账', 3"橙子生活代缴",4 "支付宝缴费",5,折减优惠,6押金转存，7预存冲抵）*
		 **/

		for (PropFeeDicDto propFeeDicDto : propFeeDics) {
			payNames.add(propFeeDicDto.getName());
		}
		return (String[]) payNames.toArray(new String[payNames.size()]);

	}
}
